<!--
 * @Author: Sam
 * @Date: 2020-08-20 12:20:37
 * @LastEditTime: 2022-01-24 12:07:00
 * @LastEditors: Sam
 * @Description:
 * @FilePath: \resourcesf:\thework\tofba-client\src\components\TableModule\index.vue
 * @<TableModule
        need-checkbox   => 选择框
        need-serial-number   => 序列号
        :table-columns="tableColumns"   => 表格头部
        :table-data="pickupInfo"        => 表格数据
        :table-operation="tableOperation" => 表格操作
        :span-method-list="spanMethodList" => 要合并的列
        :span-method-key="spanMethodKey" => 合并关键字
        @clickOperation="operationList" => 操作返回
      />

      tableColumns: [
        {prop: '',label: '', type: 'img'} 1.img, 2.tag, 3.link,4.dialog,
      ]
      pickupInfo: [  表格数据类型
        {
          // status: '待确认',    ===> 字符串
          status: {              ===> 对象
            label: '待确认',
            tag: { type: 'danger', label: '国外退件' }
          },
        }
      ],
      tableOperation: [  操作数据类型   type: svg/i/text, child是弹出框操作
        { name: 'return', tips: '打回', type: 'svg' },
        { name: 'printer', tips: '打印', type: 'i' },
        { name: 'moreOperation', tips: '更多', type: 'text', child: [ { label: '申请扣件' }, { label: '轨迹查询', route: '' } ] }
      ]
-->

<template>
  <el-table
    class="table-box"
    :max-height="maxHeight ? maxHeight : 'auto'"
    :border="true"
    :data="tableDataNew"
    style="width: 100%"
    size="mini"
    :row-class-name="tableRowClassName"
    :span-method="objectSpanMethod"
    @selection-change="handleSelectionChange"
  >
    <el-table-column v-if="needCheckbox" type="selection" align="center" />
    <el-table-column v-if="needSerialNumber" type="index" label="序号" />
    <!-- 遍历col -->
    <ex-table-column
      v-for="column in tableColumns"
      :key="column.prop"
      :auto-fit="true"
      :fit-header="true"
      :prop="column.prop"
      :label="column.label"
    >
      <template slot-scope="scope" class="column-wrapper">
        <template v-if="column.type">
          <!-- tag -->
          <template v-if="column.type === 'vue'">
            <el-tag :type="scope.row[column.prop]" effect="dark" size="mini">
              {{ scope.row[column.prop] }}
            </el-tag>
          </template>
          <!-- tag -->
          <template v-else-if="column.type === 'tag'">
            <el-tag :type="scope.row[column.prop]" effect="dark" size="mini">
              {{ scope.row[column.prop] }}
            </el-tag>
          </template>
          <!-- img -->
          <template v-else-if="column.type === 'img'">
            <el-image
              style="width: 25px; height: 25px"
              :src="sortUrl(scope.row[column.prop])"
              :preview-src-list="[sortUrl(scope.row[column.prop])]"
            >
              <div slot="error" class="image-slot">
                <i
                  class="el-icon-picture-outline"
                  :title="sortUrl(scope.row[column.prop])"
                />
              </div>
            </el-image>
          </template>
          <!-- link -->
          <template v-else-if="column.type === 'link'">
            <el-link :href="scope.row.link">{{
              scope.row[column.prop]
            }}</el-link>
          </template>
          <!-- click -->
          <template v-else-if="column.type === 'click'">
            <el-link @click="triggerClick(scope)">{{
              scope.row[column.prop]
            }}</el-link>
          </template>
          <template v-else-if="column.type === 'boolean'">
            {{
              scope.row[column.prop] == 0
                ? '否'
                : scope.row[column.prop]
                ? '是'
                : ''
            }}
          </template>
          <template v-else-if="column.type === 'popup'" />
        </template>
        <template v-else>
          <div
            class="column-content auto-fit-target"
            :title="
              scope.row[scope.column.property] &&
              Object.prototype.toString.call(
                scope.row[scope.column.property]
              ) === '[object Object]'
                ? scope.row[scope.column.property].label
                : scope.row[scope.column.property]
            "
          >
            <!-- 判断是否为对象 -->
            <div
              v-if="
                scope.row[scope.column.property] &&
                Object.prototype.toString.call(
                  scope.row[scope.column.property]
                ) === '[object Object]'
              "
            >
              {{ scope.row[scope.column.property].label }}
              <!-- 判断是否有tag -->
              <template v-if="scope.row[scope.column.property].tag">
                <el-tag
                  :type="scope.row[scope.column.property].tag.type"
                  effect="dark"
                  size="mini"
                >
                  {{ scope.row[scope.column.property].tag.label }}
                </el-tag>
              </template>
            </div>
            <!-- 非对象直接显示 -->
            <div v-else v-html="scope.row[scope.column.property]" />
          </div>
        </template>
      </template>
    </ex-table-column>

    <ex-table-column
      v-if="tableOperation.length > 0"
      :auto-fit="true"
      fixed="right"
      label="操作"
      width="150px"
    >
      <template slot-scope="scope">
        <div class="table-grid">
          <div
            v-for="(item, index) in tableOperation"
            :key="index"
            @click="onOperation(scope.row, item, scope.$index)"
          >
            <template
              v-if="
                (item.show && item.show.includes('all')) ||
                item.show.includes(scope.row.status)
              "
            >
              <div class="table-grid-item">
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  @show="showTooltip(scope.row, item, index)"
                >
                  <!-- 提示框 -->
                  <template v-if="item.child">
                    <div v-for="(d, k) in item.child" :key="k">
                      <el-button
                        v-if="
                          (d.show && d.show.includes('all')) ||
                          d.show.includes(scope.row.statusCode)
                        "
                        type="text"
                        @click.stop="onOperation(scope.row, d, scope.$index)"
                      >
                        {{ d.label }}
                      </el-button>
                    </div>
                  </template>
                  <div
                    v-else-if="
                      item.name === 's-home' && scope.row.abroadAddress
                    "
                  >
                    <div class="webui-popover-content show_remark_div">
                      <span style="color: #ff6600">海外仓地址：</span
                      >{{
                        publicData.abroadStockAddressMap[
                          scope.row.abroadAddress
                        ]
                      }}
                      <br />
                      <span style="color: #ff6600">收件人：</span
                      ><span>{{ scope.row.recipients }}</span
                      ><br />
                      <span style="color: #ff6600">联系电话：</span
                      ><span>{{
                        publicData.abroadStockLinkPhoneMap[
                          scope.row.abroadAddress + ''
                        ]
                      }}</span>
                    </div>
                  </div>

                  <div v-else>
                    {{ item.tips }}
                  </div>
                  <!-- 显示 icon/text -->

                  <div slot="reference">
                    <img
                      v-if="item.type === 'img' && scope.row.billStatus == 1"
                      src="@/assets/images/yes_bill_status_back.png"
                    />
                    <img
                      v-if="item.type === 'img' && scope.row.billStatus != 1"
                      src="@/assets/images/no_bill_status_back.png"
                    />
                    <svg-icon v-if="item.type === 'svg'" :name="item.name" />
                    <span v-else-if="item.type === 'i'">
                      <i
                        v-if="item.isColor && scope.row.abroadAddress"
                        :class="`el-icon-${item.name}`"
                        style="color: #ff6600"
                      />
                      <i v-else :class="`el-icon-${item.name}`" />
                    </span>
                    <span
                      v-else-if="item.type === 'text'"
                      class="text-blue text-underline"
                      >{{ item.tips }}</span
                    >
                  </div>
                </el-popover>
              </div>
            </template>
          </div>
        </div>
      </template>
    </ex-table-column>
  </el-table>
</template>

<script>
import { mapGetters } from 'vuex'
import globalData from '@/utils/config'
import { clone } from '@/utils/clone'
export default {
  props: {
    needCheckbox: {
      type: Boolean,
      // 需要的时候只需填写行内属性名 need-checkbox / 或者 动态填写 :need-checkbox="false/true"
      default: false,
    },
    needSerialNumber: {
      type: Boolean,
      default: false,
    },
    maxHeight: {
      type: Number,
      default: 0,
    },
    tableColumns: {
      type: Array,
      // 表格头部信息
      default: function () {
        return []
      },
    },
    tableOperation: {
      type: Array,
      // 表格操作列表
      default: function () {
        return []
      },
    },
    tableData: {
      type: Array,
      // 表格数据
      default: function () {
        return []
      },
    },
    spanMethodList: {
      type: Array,
      // 要合并的列
      default: function () {
        return []
      },
    },
    spanMethodKey: {
      type: String,
      // 合并关键字
      default: '',
    },
    multipleSelection: {
      type: Array,
      // 选择的数据
      default: function () {
        return []
      },
    },
  },
  data() {
    return {
      tableDataNew: [],
      spanArr: [],
      pos: 0,
    }
  },
  computed: {
    ...mapGetters(['publicData']),
  },
  watch: {
    tableData: {
      handler(newValue, oldValue) {
        console.log('newValue :>> ', newValue)
        if (newValue) {
          this.tableDataNew = clone(newValue)
          this.getSpanArr()
        }
      },
      deep: true,
    },
  },
  filters: {},

  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (row.status && row.status === -10) {
        return 'warning-row'
      }
      return ''
    },
    sortUrl(value) {
      if (!value) return ''
      const url =
        value.indexOf('http') > -1 ? value : globalData.fileUrl + value
      return url
    },
    onOperation(data, item, index) {
      this.$emit('clickOperation', data, item, index)
    },
    showTooltip(data, item, index) {
      if (item.name === 'eye-open') {
        console.log('show eye-open', data)

        if (!data.otherInfo) {
          this.$emit('clickOperation', data, item, index)
        }
      }
    },
    handleSelectionChange(val) {
      this.$emit('update:multipleSelection', val)
    },
    triggerClick(s) {
      this.$emit('triggerClick', s)
    },
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.spanMethodList.includes(columnIndex)) {
        const spanMethodKey = this.spanMethodKey
        const target = this.tableDataNew.find(
          (x) => x[spanMethodKey] === row[spanMethodKey]
        )
        return {
          rowspan: target ? this.spanArr[rowIndex] : 1,
          colspan: 1,
        }
      }
    },
    async getSpanArr(obj) {
      const spanMethodKey = this.spanMethodKey
      // 数据排序，以便合并
      if (this.tableDataNew && this.tableDataNew.length > 0) {
        let spanArr = []
        let pos = 0

        this.tableDataNew.sort(
          (a, b) => parseFloat(a[spanMethodKey]) - parseFloat(b[spanMethodKey])
        )
        spanArr = []
        pos = 0
        for (var i = 0; i < this.tableDataNew.length; i++) {
          if (i === 0) {
            spanArr.push(1)
            pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]

            if (
              this.tableDataNew[i][spanMethodKey] ===
              this.tableDataNew[i - 1][spanMethodKey]
            ) {
              spanArr[pos] += 1
              spanArr.push(0)
            } else {
              spanArr.push(1)
              pos = i
            }
          }
        }
        this.spanArr = spanArr
        this.pos = pos
        console.log('spanArr :>> ', spanArr)
      }
    },
  },
}
</script>

<style lang="scss">
.table-grid {
  display: flex;
  .table-grid-item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 4px;
    // height: 16px;
    text-align: center;
    // width: 16px;
    float: left;
    font-size: 14px;
    color: #24292e;
    cursor: pointer;
  }
}
</style>
